package store.dao;

import store.model.Account;
import store.model.Recover;

import java.sql.SQLException;
import java.util.List;

public class AccountDao {

    private static DBUtils<Account> dbUtils;
    private static final Recover<Account> accountRecover = new Account.AccountRecover();

    public AccountDao() {
        if (dbUtils == null) {
            dbUtils = new DBUtils<>();
        }
    }

    public Account login(String phone, String password) throws SQLException, ClassNotFoundException {
        String sql = "select * from account where phone = ? and password = ?";
        List<Account> accounts = dbUtils.executeQuery1(sql, accountRecover , phone, password);
        return accounts.size() > 0 ? accounts.get(0) : null;
    }

    public int insert(Account account) throws SQLException, ClassNotFoundException {
        String sql = "insert into account(phone,password,name) values(?,?,?)";
        Object[] values = new Object[]{
                account.getPhone(), account.getPassword(), account.getName()
        };
        return dbUtils.executeUpdate(sql, values);
    }

    public int updatePoint(Account account) throws SQLException, ClassNotFoundException {
        String sql = "update account set point = ? where id = ?";
        return dbUtils.executeUpdate(sql, account.getPoint(), account.getId());
    }

    public int delete(int id) throws SQLException, ClassNotFoundException {
        String sql = "delete from account where id = ?";
        return dbUtils.executeUpdate(sql, id);
    }

    public Account checkRegister(String phone) throws SQLException, ClassNotFoundException {
        String sql = "select * from account where phone = ?";
        List<Account> accounts = dbUtils.executeQuery1(sql, accountRecover, phone);
        if (accounts.size() > 0) {
            return accounts.get(0);
        }
        return null;

    }

    public List<Account> selectAll() throws SQLException, ClassNotFoundException {
        String sql = "select * from account where type = ?";
        return dbUtils.executeQuery1(sql, accountRecover, 1);
    }

}
